import {
  SHOPCART_GET_DATA,
  SHOPCART_UPDATE_ITEM,
  SHOPCART_CHECKED_ALL,
  SHOPCART_CALCULATE_PRICE,
  SHOPCART_REMOVE_ITEM,
  SHOPCART_BALANCE
} from '../mutation-types';
// import request from '../../utils/wxRequest';
import { getShopCartList, deleteShopFromCartApi, balanceShopApi } from '../../api';

function getInitialState() {
  return {
    data: {},
    totalPrice: 0.00,
    selectCount: 0,
    list: [],
    currentPage: 1,
    pageCount: 1,
    hasNextPage: null,
    loading: false,
    noData: true
  };
}

const state = getInitialState();

const getters = {
  data: (state) => state.data,
  totalPrice: (state) => state.totalPrice,
  selectCount: (state) => state.selectCount,
  menu: (state) => state.menu,
  list: (state) => state.list,
  loading: (state) => state.loading,
  hasNextPage: (state) => state.hasNextPage,
  noData: (state) => state.noData,
  currentPage: (state) => state.currentPage
};

const mutations = {
  [SHOPCART_GET_DATA](state, payload) {
    console.log(state);
    console.log(payload);
    state.currentPage = payload.currentPage;
    state.pageCount = payload.pageCount;
    if (payload.items.length !== 0) {
      state.hasNextPage = payload.hasNextPage;
    } else {
      state.hasNextPage = null;
    }
    const oldList = state.list;
    state.list = oldList.concat(payload.items);
    state.noData = payload.noData;
    state.loading = false;
    console.log('now state: -> ', state);

    // state.data = payload.data;
  },
  [SHOPCART_UPDATE_ITEM](state, payload) {
    state.list[payload.idx] = payload.item;
    console.log(state.list);
  },
  [SHOPCART_CHECKED_ALL](state, payload) {
    console.log('check all start');
    const tempData = state.list;
    for (let i = 0, len = tempData.length; i < len; i++) {
      tempData[i].checked = payload.checked;
    }
    state.data = tempData;
    console.log('check all end');
  },
  [SHOPCART_CALCULATE_PRICE](state, payload) {
    console.log('开始计算价格');
    let totalPrice = 0.00;
    let selectCount = 0;
    const tempData = state.list;
    for (let i = 0, len = tempData.length; i < len; i++) {
      if (tempData[i].checked === true) {
        totalPrice += tempData[i].num * tempData[i].price;
        selectCount += 1;
      }
    }

    state.totalPrice = totalPrice.toFixed(2);
    state.selectCount = selectCount;
  },
  loading(state) {
    state.loading = true;
  },
  destroyedState(state) {
    state = Object.assign(state, getInitialState());
    console.log('destroyed state: -> ', state);
  },
  [SHOPCART_REMOVE_ITEM](state, payload) {
  }
};

const actions = {
  [SHOPCART_GET_DATA]({ commit }, data) {
    commit({type: 'loading'});
    console.log(data);
    getShopCartList(data.page)
      .then(res => {
        console.log(res);
        const currentPage = res.data.meta.currentPage;
        const pageCount = res.data.meta.pageCount;
        const hasNextPage = currentPage < pageCount && currentPage !== 0;
        commit({
          type: SHOPCART_GET_DATA,
          items: res.data.items,
          currentPage: currentPage,
          pageCount: pageCount,
          hasNextPage: hasNextPage,
          noData: res.data.items.length === 0
        });
        commit({
          type: SHOPCART_CALCULATE_PRICE
        });
      });
  },
  [SHOPCART_UPDATE_ITEM]({ commit }, params) {
    console.log('准备更新');
    commit({
      type: SHOPCART_UPDATE_ITEM,
      item: params.item,
      idx: params.idx
    });
    commit({
      type: SHOPCART_CALCULATE_PRICE
    });
  },
  [SHOPCART_CHECKED_ALL]({ commit }, params) {
    console.log('全选商品action');
    commit({
      type: SHOPCART_CHECKED_ALL,
      checked: params.checked
    });
    commit({
      type: SHOPCART_CALCULATE_PRICE
    });
  },
  // 在请求参数切换时，清空list数据
  destroyedState({ commit }) {
    commit({
      type: 'destroyedState'
    });
  },
  [SHOPCART_REMOVE_ITEM]({ commit, state, dispatch }) {
    let willRemoveArr = [];
    const tempData = state.list;
    for (let i = 0, len = tempData.length; i < len; i++) {
      if (tempData[i].checked === true) {
        willRemoveArr.push(tempData[i].id);
      }
    }

    deleteShopFromCartApi({
      ids: willRemoveArr
    })
      .then(res => {
        console.log(res);
        dispatch('destroyedState');
        dispatch(SHOPCART_GET_DATA, {
          page: 1
        });
      })
      .catch(e => {
        console.log(e);
      });
    console.log('将要删除的商品数组: ', willRemoveArr);
    commit({
      type: SHOPCART_CALCULATE_PRICE
    });
  },
  [SHOPCART_BALANCE]({ commit, state }) {
    let goods = [];
    const tempData = state.list;
    for (let i = 0, len = tempData.length; i < len; i++) {
      if (tempData[i].checked === true) {
        goods.push({ id: tempData[i].id, num: tempData[i].num });
      }
    }
    console.log('将要结算的商品数组: ', goods);

    balanceShopApi({
      items: goods
    }).then(res => {
      console.log(res);
      wx.navigateTo({
        url: '/pages/createOrder'
      });
    }).catch(e => {
      console.log(e);
    });
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
